﻿using System;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Reflection;
using System.Collections.Generic;
using System.Configuration.Install;

namespace YEA.Utilities.Common
{
    public static class UtilitiesHelper
    {
        public static string GetMyProgramFullName()
        {
            var first = Assembly.GetEntryAssembly();
            return first.FullName.Split(',')[0];
        }
        /// <summary>
        /// Standard installer for applications, replaces InstallUtil, especially helpfull for installing services or WMI instrumented applications
        /// </summary>
        /// <param name="type">The type to be installed</param>
        /// <param name="install">install if true, otherwise uninstall</param>
        public static void Install(Type type, bool install)
        {
            var installArgs = new List<string>();
            installArgs.Add( string.Format("/logfile={0}.installLog.txt", type.FullName));
            installArgs.Add("/LogToConsole=true");
            installArgs.Add("/ShowCallStack=true");
            installArgs.Add(type.Assembly.Location);
            if (!install)
                installArgs.Add( "/u");
            ManagedInstallerClass.InstallHelper(installArgs.ToArray());
        }
        public static string GetConfigValue(string key, string defaultValue, bool throwExceptionIfNull)
        {
            var val = ConfigurationManager.AppSettings[key];
            if( string.IsNullOrEmpty( val) )
            {
                if( throwExceptionIfNull )
                    throw new ConfigurationErrorsException(string.Format("couldn't read the configuration key.  Please add a value to config key {0} in your configuration file", key));
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings.Add(key, defaultValue);
                config.Save(ConfigurationSaveMode.Modified);
            }
            return val;
        }
        public static string ValidateValue(string value, string pattern)
        {
            if( TryValidateValue( value, pattern) )
                return value;
            throw new FormatException(string.Format("The value {0} needs to conform to the pattern {1}", value, pattern));
        }
        public static bool TryValidateValue(string value, string pattern)
        {
            var reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            var match = reg.Match(value);
            return match.Success;
        }
    }
}
